package org.babygo.file;

import com.ape.babygo.api.BasePackage;
import org.babygo.file.protocol.FilePackage;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;


public class FileObj {
    private short fileId;
    private RandomAccessFile randomAccessFile;
    private File file;
    private int packageId;
    private long totalPackageNum;
    private long fileLength;
    private long filePointer;

    public FileObj(File file) throws FileNotFoundException {
        this.fileId = IdCreator.getId();
        this.randomAccessFile = new RandomAccessFile(file, "rw");
        this.file = file;
        this.totalPackageNum = file.length() / FilePackage.DATA_SIZE_DEFAULT_SIZE + 1;
    }

    public BasePackage read() {
        FilePackage filePackage = new FilePackage();
        byte[] fileData = getFileDataArr();
        if (fileData == null){
            return null;
        }

        filePackage.packBody(fileData);

        filePackage.packHead(fileId, packageId, totalPackageNum);

        BasePackage dataPackage = new BasePackage();
        dataPackage.packing(BasePackage.FILE, filePackage.toBinaryPackage());

        packageId = packageId + 1;
        return dataPackage;
    }

    private byte[] getFileDataArr() {
        long loadLength = 0;
        byte[] fileData = null;
        try {
            loadLength = fileLength - filePointer;
            System.out.println(filePointer + "---" + fileLength);
            if (loadLength < FilePackage.DATA_SIZE_DEFAULT_SIZE) {
                fileData = new byte[(int) loadLength];
                filePointer = filePointer + loadLength;
            } else {
                fileData = new byte[FilePackage.DATA_SIZE_DEFAULT_SIZE];
                filePointer = filePointer + FilePackage.DATA_SIZE_DEFAULT_SIZE;
            }
            randomAccessFile.read(fileData);
        } catch (IOException e) {
            System.out.println("read file error!" + e.getMessage());
        }
        return fileData;
    }

    public boolean readable() {
        if (fileLength == 0){
            try {
                fileLength = randomAccessFile.length();
                filePointer = randomAccessFile.getFilePointer();
            } catch (IOException e) {
                System.out.println("readable() error!" + e.getMessage());
                return false;
            }
        }
        return filePointer < fileLength;
    }
}